package com.lp.easymethodlink.ui;

import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.lp.easymethodlink.model.CallHierarchyNode;
import com.lp.easymethodlink.service.MarkdownExportService;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 调用链路工具窗口面板
 */
public class CallHierarchyToolWindowPanel extends JPanel {
    
    public static final Key<CallHierarchyToolWindowPanel> KEY = Key.create("CallHierarchyToolWindow");
    
    private final Project project;
    private CallHierarchyPanel hierarchyPanel;
    private JLabel statusLabel;
    private JButton exportButton;
    private CallHierarchyNode currentRootNode;  // 保存当前的调用链路数据
    private MarkdownExportService exportService;
    
    public CallHierarchyToolWindowPanel(Project project) {
        this.project = project;
        this.exportService = new MarkdownExportService();
        initializeUI();
    }
    
    private void initializeUI() {
        setLayout(new BorderLayout());
        
        // 创建顶部面板（标题 + 导出按钮）
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 创建标题标签
        JLabel titleLabel = new JLabel("方法调用链路分析", SwingConstants.CENTER);
        titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 14f));
        titleLabel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        topPanel.add(titleLabel, BorderLayout.CENTER);
        
        // 创建导出按钮
        exportButton = new JButton("导出为Markdown");
        exportButton.setEnabled(false);
        exportButton.addActionListener(e -> exportToMarkdown());
        exportButton.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        topPanel.add(exportButton, BorderLayout.EAST);
        
        add(topPanel, BorderLayout.NORTH);
        
        // 创建调用链路面板
        hierarchyPanel = new CallHierarchyPanel();
        add(hierarchyPanel, BorderLayout.CENTER);
        
        // 创建底部面板（状态标签 + 署名）
        JPanel bottomPanel = new JPanel(new BorderLayout());
        
        // 创建状态标签
        statusLabel = new JLabel("请选择一个方法并右键选择'分析方法调用链路'", SwingConstants.CENTER);
        statusLabel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
        statusLabel.setForeground(Color.GRAY);
        bottomPanel.add(statusLabel, BorderLayout.CENTER);
        
        // 创建署名标签
        JLabel signatureLabel = new JLabel("（微信公众号，小红书：乐拍）", SwingConstants.CENTER);
        signatureLabel.setFont(signatureLabel.getFont().deriveFont(Font.PLAIN, 11f));
        signatureLabel.setForeground(Color.GRAY);
        signatureLabel.setBorder(BorderFactory.createEmptyBorder(0, 8, 4, 8));
        bottomPanel.add(signatureLabel, BorderLayout.SOUTH);
        
        add(bottomPanel, BorderLayout.SOUTH);
        
        // 设置初始状态
        hierarchyPanel.setVisible(false);
    }
    
    /**
     * 显示调用链路
     * @param rootNode 根节点
     */
    public void displayCallHierarchy(CallHierarchyNode rootNode) {
        this.currentRootNode = rootNode;  // 保存当前数据
        
        SwingUtilities.invokeLater(() -> {
            if (rootNode != null && !rootNode.getChildren().isEmpty()) {
                hierarchyPanel.displayCallHierarchy(rootNode);
                hierarchyPanel.setVisible(true);
                statusLabel.setText("找到 " + rootNode.getChildren().size() + " 个调用者");
                statusLabel.setForeground(Color.BLACK);
                exportButton.setEnabled(true);  // 启用导出按钮
            } else {
                hierarchyPanel.setVisible(false);
                statusLabel.setText("未找到调用者");
                statusLabel.setForeground(Color.RED);
                exportButton.setEnabled(false);  // 禁用导出按钮
            }
            revalidate();
            repaint();
        });
    }
    
    /**
     * 清空显示内容
     */
    public void clearDisplay() {
        SwingUtilities.invokeLater(() -> {
            hierarchyPanel.setVisible(false);
            statusLabel.setText("请选择一个方法并右键选择'分析方法调用链路'");
            statusLabel.setForeground(Color.GRAY);
            exportButton.setEnabled(false);
            currentRootNode = null;
            revalidate();
            repaint();
        });
    }
    
    /**
     * 导出为Markdown文档
     */
    private void exportToMarkdown() {
        if (currentRootNode == null) {
            Messages.showMessageDialog(
                project,
                "没有可导出的调用链路数据",
                "错误",
                Messages.getErrorIcon()
            );
            return;
        }
        
        try {
            // 使用文件选择器选择保存位置
            FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
            descriptor.setTitle("选择保存目录");
            descriptor.setDescription("选择Markdown文件的保存目录");
            
            VirtualFile[] selectedFiles = FileChooserFactory.getInstance()
                .createFileChooser(descriptor, project, null)
                .choose(project);
            
            if (selectedFiles.length > 0) {
                VirtualFile selectedDir = selectedFiles[0];
                
                // 生成文件名 - 动态生成，根据实际的类名和方法名
                String fileName = currentRootNode.getClassName() + "类的" + 
                    currentRootNode.getMethodName() + "方法调用链路分析报告.md";
                
                File outputFile = new File(selectedDir.getPath(), fileName);
                
                // 生成Markdown内容
                String markdown = exportService.exportToMarkdown(currentRootNode);
                
                // 保存到文件
                exportService.saveToFile(markdown, outputFile);
                
                // 显示成功消息
                Messages.showMessageDialog(
                    project,
                    "导出成功！\n文件保存到: " + outputFile.getAbsolutePath(),
                    "成功",
                    Messages.getInformationIcon()
                );
                
                // 刷新虚拟文件系统
                selectedDir.refresh(false, true);
            }
        } catch (Exception e) {
            Messages.showMessageDialog(
                project,
                "导出失败: " + e.getMessage(),
                "错误",
                Messages.getErrorIcon()
            );
            e.printStackTrace();
        }
    }
}